<script lang="ts" setup>
import { computed, defineEmits, defineProps, ref } from "vue";
import FirstPageIcon from "@/assets/svg/pagination/first_page.svg?component";
import LastPageIcon from "@/assets/svg/pagination/last_page.svg?component";
import PrePageIcon from "@/assets/svg/pagination/pre_page.svg";

defineOptions({
  name: "RePagination"
});

// Props 定义
const props = defineProps({
  total: {
    type: Number,
    required: true
  },
  defaultPage: {
    type: Number,
    default: 1
  },
  defaultPageSize: {
    type: Number,
    default: 10
  },
  layout: {
    type: String,
    default: "prev, pager, next, sizes, total"
  },
  pageSizes: {
    type: Array as () => number[],
    default: () => [10, 20, 50, 100]
  },
  background: {
    type: Boolean,
    default: true
  },
  showFirstLast: {
    type: Boolean,
    default: true // 是否显示跳转到首尾页按钮
  }
});

// Emits 定义
const emit = defineEmits<{
  (event: "update:currentPage", currentPage: number): void;
  (event: "update:pageSize", pageSize: number): void;
  (event: "pagination-change", data: { currentPage: number; pageSize: number }): void;
}>();

// 内部状态
const currentPage = ref<number>(props.defaultPage);
const pageSize = ref<number>(props.defaultPageSize);

// 计算总页数
const totalPages = computed(() => Math.ceil(props.total / pageSize.value));

// 方法定义
const handlePageChange = (page: number) => {
  currentPage.value = page;
  emit("update:currentPage", page);
  emit("pagination-change", {
    currentPage: currentPage.value,
    pageSize: pageSize.value
  });
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  emit("update:pageSize", size);
  emit("pagination-change", {
    currentPage: currentPage.value,
    pageSize: pageSize.value
  });
};

// 跳转到首页
const goToFirstPage = () => {
  handlePageChange(1);
};

// 跳转到尾页
const goToLastPage = () => {
  handlePageChange(totalPages.value);
};
</script>
<template>
  <div class="pagination-container">
    <el-button v-if="showFirstLast" size="small" :disabled="currentPage === 1" text style="padding: 0; margin: 0; width: 100%; height: 100%" @click="goToFirstPage">
      <!--todo 首尾页不可用,可以状态下不同的图标，缺少-->
      <FirstPageIcon />
    </el-button>

    <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total" :layout="layout" :page-sizes="pageSizes" :background="background" :prev-icon="PrePageIcon" @current-change="handlePageChange" @size-change="handleSizeChange" />

    <el-button v-if="showFirstLast" size="small" :disabled="currentPage === totalPages" text style="padding: 0; margin: 0; width: 100%; height: 100%" @click="goToLastPage">
      <LastPageIcon />
    </el-button>
  </div>
</template>

<style scoped>
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}
</style>
